//
//  SHPhotoBrowserCell.m
//  Tradeaider
//
//  Created by 王方伟 on 2017/7/12.
//  Copyright © 2017年 Shinyhub. All rights reserved.
//

#import "SHPhotoBrowserCell.h"
#import "UIImageView+WebCache.h"
#import "UIView+Extension.h"
#import "FWProgressView.h"
#import "SDImageCache.h"

//屏幕尺寸
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height

@interface SHPhotoBrowserCell ()<UIScrollViewDelegate, UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollerView;
@property (weak, nonatomic) IBOutlet FWProgressView *progressView;
/** 记录pan手势开始时imageView的位置 */
@property (assign, nonatomic) CGRect beganFrame;
/** 记录pan手势开始时，手势位置 */
@property (assign, nonatomic) CGPoint beganTouch;

@property (assign, nonatomic) CGSize fitSize;
@property (assign, nonatomic) CGRect fitFrame;
@property (assign, nonatomic) CGPoint centerOfContentSize;
@end

@implementation SHPhotoBrowserCell

- (CGSize)fitSize{
    if (_imageView.image) {
        CGSize size = _imageView.image.size;
        CGFloat width = _scrollerView.bounds.size.width;
        CGFloat scale = size.height / size.width;
        return CGSizeMake(width, scale * width);
    }
    return CGSizeZero;
}

- (CGRect)fitFrame{
    CGSize size = self.fitSize;
    CGFloat y = (_scrollerView.bounds.size.height - size.height) > 0 ? (_scrollerView.bounds.size.height - size.height) * 0.5 : 0;
    return CGRectMake(0, y, size.width, size.height);
}

- (CGPoint)centerOfContentSize{
    CGFloat deltaWidth = self.bounds.size.width - _scrollerView.contentSize.width;
    CGFloat offsetX = deltaWidth > 0 ? deltaWidth * 0.5 : 0;
    CGFloat deltaHeight = self.bounds.size.height - _scrollerView.contentSize.height;
    CGFloat offsetY = deltaHeight > 0 ? deltaHeight * 0.5 : 0;
    
    return CGPointMake(_scrollerView.contentSize.width * 0.5 + offsetX, _scrollerView.contentSize.height * 0.5 + offsetY);
}

- (UIImageView *)imageView{
    if (_imageView == nil) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.frame = self.contentView.bounds;
        imageView.userInteractionEnabled = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.scrollerView insertSubview:imageView belowSubview:_progressView];
        _imageView = imageView;
    }
    return _imageView;
}

- (void)setPlaceholderImage:(UIImage *)placeholderImage hightUrl:(NSURL *)hightUrl originalUrl:(NSURL *)originalUrl{
    UIImage *placeholder = placeholderImage;
    NSURL *url = hightUrl;
    UIImage *cacheImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:originalUrl.absoluteString];
    if (cacheImage) {
        url = originalUrl;
    }else{
        cacheImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:hightUrl.absoluteString];
        url = hightUrl;
    }
    
    if (cacheImage) {
        placeholder = cacheImage;
    }
    
    if (url == nil) {
        url = originalUrl;
    }
    
    if (url == nil) {
        self.imageView.image = placeholder;
        [self updateViewLayout];
        return;
    }
    
    [self.imageView sd_setImageWithURL:url placeholderImage:placeholderImage options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        CGFloat progress = 1.0 * receivedSize / expectedSize;
        [self.progressView setProgress:progress];
    } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (image) {
            if (_downloadFinishBlock) _downloadFinishBlock();
            self.progressView.hidden = YES;
            [self updateViewLayout];
        }
    }];
}


- (void)updateViewLayout{
    _scrollerView.frame = self.contentView.bounds;
    [_scrollerView setZoomScale:1.0 animated:FALSE];
    _imageView.frame = [self fitFrame];
    [_scrollerView setZoomScale:1.0 animated:FALSE];
    
}

- (void)awakeFromNib{
    [super awakeFromNib];
    UITapGestureRecognizer *singleTap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didSingleTap)];
    [self.contentView addGestureRecognizer:singleTap];
    
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didDoubleTap:)];
    doubleTap.numberOfTapsRequired = 2;
    [singleTap requireGestureRecognizerToFail:doubleTap];
    [self.contentView addGestureRecognizer:doubleTap];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
    pan.delegate = self;
    [_scrollerView addGestureRecognizer:pan];
    
    UILongPressGestureRecognizer *longPan = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onClickLongPan:)];
    [self.contentView addGestureRecognizer:longPan];
    
    self.scrollerView.delegate = self;
    self.scrollerView.maximumZoomScale = 3.0;
    self.scrollerView.multipleTouchEnabled = YES;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    [self updateViewLayout];
}

#pragma mark 单击手势
- (void)didSingleTap{
    if ([_delegate respondsToSelector:@selector(onClickSingleTap:)]) {
        [_delegate onClickSingleTap:self];
    }
}

#pragma mark 双击手势
- (void)didDoubleTap:(UITapGestureRecognizer *)tap{
    if (self.scrollerView.zoomScale > 1.0) {
        [self.scrollerView setZoomScale:1.0 animated:YES];
    }else {
        CGPoint touchPoint = [tap locationInView:self.imageView];
        CGFloat newZoomScale = self.scrollerView.maximumZoomScale;
        CGFloat xsize = self.width / newZoomScale;
        CGFloat ysize = self.height / newZoomScale;
        [self.scrollerView zoomToRect:CGRectMake(touchPoint.x - xsize * 0.5, touchPoint.y - ysize * 0.5, xsize, ysize) animated:YES];
        
    }
}

#pragma mark 长按手势
- (void)onClickLongPan:(UILongPressGestureRecognizer *)sender{
    if (sender.state == UIGestureRecognizerStateBegan) {
        if ([_delegate respondsToSelector:@selector(photoBrowserCell:didLongPressWith:)]) {
            [_delegate photoBrowserCell:self didLongPressWith:_imageView.image];
        }
    }
    
}


#pragma mark UIScrollView 代理
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    _imageView.center = self.centerOfContentSize;
}

#pragma mark UIGestureRecognizerDelegate
- (void)panGesture:(UIPanGestureRecognizer *)pan{
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
            _beganFrame = _imageView.frame;
            _beganTouch = [pan locationInView:self];
            break;
            
        case UIGestureRecognizerStateChanged:{
            // 拖动偏移量
            CGPoint translation = [pan translationInView:_scrollerView];
            CGPoint currentTouch = [pan locationInView:_scrollerView];
            // 由下拉的偏移值决定缩放比例，越往下偏移，缩得越小。scale值区间[0.3, 1.0]
            CGFloat scale = MIN(1.0, MAX(0.3, 1 - translation.y / self.bounds.size.height));
            
            CGFloat width = _beganFrame.size.width * scale;
            CGFloat height = _beganFrame.size.height * scale;
            
            CGFloat xRate = (_beganTouch.x - _beganFrame.origin.x) / _beganFrame.size.width;
            CGFloat currentTouchDeltaX = xRate * width;
            CGFloat x = currentTouch.x - currentTouchDeltaX;
            
            CGFloat yRate = (_beganTouch.y - _beganFrame.origin.y) / _beganFrame.size.height;
            CGFloat currentTouchDeltaY = yRate * height;
            CGFloat y = currentTouch.y - currentTouchDeltaY;
            
            _imageView.frame = CGRectMake(x, y, width, height);
            if ([_delegate respondsToSelector:@selector(onPanTap:scale:)]) {
                [_delegate onPanTap:self scale:scale];
            }
            
        }
            break;
            
        case UIGestureRecognizerStateEnded : case UIGestureRecognizerStateCancelled:{
            if ([pan velocityInView:self].y > 50) {
                [self didSingleTap];
            }else{
                [self endPan];
            }
        }
            break;
            
        
          
            break;
            
        case UIGestureRecognizerStateFailed:
           
            break;
            
        case UIGestureRecognizerStatePossible:
           
            break;
            
        default:
            [self endPan];
            break;
            
    }
    
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        UIPanGestureRecognizer *pan = (UIPanGestureRecognizer *)gestureRecognizer;
        CGPoint velocity = [pan velocityInView:self];
        if (velocity.y < 0) {
            return FALSE;
        }
        
        if (abs((int)velocity.x) > (int)velocity.y) {
            return FALSE;
        }
        
        if (_scrollerView.contentOffset.y > 0) {
            return FALSE;
        }
        return TRUE;
    }
    return TRUE;
}

- (void)endPan{
    if ([_delegate respondsToSelector:@selector(onPanTap:scale:)]) {
        [_delegate onPanTap:self scale:1.0];
    }
    [UIView animateWithDuration:0.25 animations:^{
        self.imageView.frame = self.fitFrame;
    }];
}

@end
